<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, shallowRef } from "vue";
import * as echarts from "echarts";

const chartRef = ref(null);
const chartInstance = shallowRef(null);
const timer = ref(null);
const currentGroupIndex = ref(0);
const allData = ref([]);
const provinces = ref([]);

// 获取数据
const fetchData = async () => {
  try {
    const response = await fetch('http://localhost:8082/logistics/provinceRanking');
    const result = await response.json();
    return result.code === 200 ? result.data : [];
  } catch (error) {
    console.error('数据获取失败:', error);
    return [];
  }
};

// 初始化图表
const initChart = async () => {
  if (chartInstance.value) return;
  
  chartInstance.value = echarts.init(chartRef.value);
  await updateChart();
};

// 更新图表数据
const updateChart = async () => {
  const data = await fetchData();
  if (data.length === 0) return;
  
  allData.value = data.map(item => item.businessCount);
  provinces.value = data.map(item => item.provinceName);
  
  // 处理数据分组（每组最多显示5条）
  const groupSize = 5;
  const groups = [];
  for (let i = 0; i < provinces.value.length; i += groupSize) {
    groups.push({
      provinces: provinces.value.slice(i, i + groupSize),
      data: allData.value.slice(i, i + groupSize)
    });
  }
  
  // 如果没有分组数据，使用完整数据
  const currentGroup = groups.length > 0 
    ? groups[currentGroupIndex.value % groups.length] 
    : { provinces: provinces.value, data: allData.value };
  
  const option = {
    color: ["#00bfff"],
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" }
    },
    yAxis: {
      type: "category",
      data: currentGroup.provinces,
      axisLine: { lineStyle: { color: "#00bfff" } },
      axisLabel: {
        color: "#00bfff",
        fontSize: getResponsiveFontSize()
      }
    },
    xAxis: {
      type: "value",
      axisLine: { lineStyle: { color: "#00bfff" } },
      axisLabel: {
        color: "#00bfff",
        fontSize: getResponsiveFontSize()
      },
      splitLine: { lineStyle: { color: "rgba(0, 0, 0, 0.3)" } }
    },
    series: [{
      data: currentGroup.data,
      type: "bar",
      label: {
        show: true,
        position: "insideRight",
        color: "#fff",
        fontSize: getResponsiveFontSize(12, 10)
      },
      itemStyle: { borderRadius: [0, 10, 10, 0] }
    }],
    grid: {
      left: "10%",
      right: "10%",
      bottom: "10%",
      containLabel: true
    }
  };
  
  chartInstance.value.setOption(option);
};

// 启动数据轮播
const startDataSwitching = () => {
  timer.value = setInterval(() => {
    currentGroupIndex.value++;
    updateChart();
  }, 2000);
};

// 响应式字体大小
const getResponsiveFontSize = (large = 14, small = 12) => {
  return window.innerWidth < 768 ? small : large;
};

// 窗口大小变化时重绘图表
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize();
    updateChart();
  }
};

onMounted(async () => {
  await initChart();
  startDataSwitching();
  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  if (timer.value) clearInterval(timer.value);
  if (chartInstance.value) chartInstance.value.dispose();
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped lang="less">
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px; /* 确保有最小高度 */
}

:deep(.echarts-fullscreen) {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background-color: #000;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  margin: 0;
}

:deep(.echarts-fullscreen .chart) {
  width: 100%;
  height: 100%;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
}
</style>